package com.heima.skydemo.InterceptorRegistry;

import com.heima.skydemo.domin.common.BaseContest;
import com.heima.skydemo.entity.JwtProperties;
import com.heima.skydemo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtInterceptorRegistry implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try {
            log.info("token令牌校验:{}",token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //此处涉及到一个问题，在claims中获取的empId是Integer类型，而BaseContest.setContestId(empId1)中的empId是Long类型，所以需要将empId转换为Long类型，如果用（Long）强转会抛异常
            Integer empId = (Integer) claims.get("empId");
            Long empId1 = Long.valueOf(empId);
            BaseContest.setContestId(empId1);
            return true;
        } catch (Exception e) {
            log.error("token令牌校验失败:{}",token);
           response.setStatus(401);
            return false;
        }

    }
}
